package com.runshu.newsmartark.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.ProDetailAdapter;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.entity.CategoryListEntity;
import com.runshu.newsmartark.entity.HwInfoUtils;
import com.runshu.newsmartark.entity.InventoryDetailEntity;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.entity.ProDetailEntity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.GetStorageContract;
import com.runshu.newsmartark.mvp.contract.ProDetailContract;
import com.runshu.newsmartark.mvp.model.GetStorageModel;
import com.runshu.newsmartark.mvp.model.ProDetailModel;
import com.runshu.newsmartark.mvp.presenter.GetStoragePresenter;
import com.runshu.newsmartark.mvp.presenter.ProDetailPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.RecyclerViewNoBugLinearLayoutManager;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.TopTitleBar;
import com.zxl.library.DropDownMenu;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.com.example.rfid.driver.Driver;
import cn.com.example.rfid.driver.RfidDriver;

/**
 * Demo class
 *
 * @author yu
 * @date 12/2/20
 * @decs：
 */
@BindEventBus
public class ProDetailActivity extends BaseActivity implements GetStorageContract.View, ProDetailContract.View {
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.tv_pro_name)
    TextView mTvProName;
    @BindView(R.id.rela_name_hint)
    RelativeLayout mRelaNameHint;
    @BindView(R.id.tv_pro_guige)
    TextView mTvProGuige;
    @BindView(R.id.rela_pihao_hint)
    RelativeLayout mRelaPihaoHint;
    @BindView(R.id.tv_pro_company)
    TextView mTvProCompany;
    @BindView(R.id.tv_pro_num)
    TextView mTvProNum;
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    private String headers[];
    private String selectTypeOne[];
    //    0全部", "1最近一个月", "2最近三个月", "3自定义"
    private String selectTypeTwo[];
    private View contentView;
    private int[] types ;
    private ProDetailAdapter mAdapter;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipe_layout;
    private List<InventoryDetailEntity.ListBean> mData;
    private int pageSize = 20;
    private int pageNum = 1;
    private boolean loading = true;
    private boolean isLoadMore = false;
    private String mac;
    private GetStoragePresenter storagePresenter;
    private String manufacturer, productNo, model, stockName, productName,goodsId;
    private int stockNameID, expiryDate;
    private Intent intent;
    private ProDetailPresenter detailPresenter;
    private List<CategoryListEntity> StockSelList;
    private int type = 0;
    Driver driver;
    @Override
    protected int getLayoutId() {
        return R.layout.act_prodetail;
    }

    @Override
    protected void initView() {
     driver = new RfidDriver();
        detailPresenter = new ProDetailPresenter(this, new ProDetailModel());
        intent = getIntent();
        if (intent != null) {
            manufacturer = intent.getStringExtra("manufacturer");
            productNo = intent.getStringExtra("productNo");
            model = intent.getStringExtra("model");
            stockNameID = intent.getIntExtra("stockNameID", 0);
            expiryDate = intent.getIntExtra("expiryDate", 0);
            productName = intent.getStringExtra("productName");
            type = intent.getIntExtra("type", 0);
            stockName = intent.getStringExtra("stockName");
            goodsId = intent.getStringExtra("goodsId");
            mTvProName.setText(productName);
        }
        StockSelList = new ArrayList<>();
        mac = MacUtils.getFormatMacAddr();
        mToolbar.setTitle("库存明细");
        mToolbar.setIsShowBac(true);
        contentView = getLayoutInflater().inflate(R.layout.content_logs_manager, null);
        swipe_layout = contentView.findViewById(R.id.swipe_layout);
        recyclerView = contentView.findViewById(R.id.recy_logs);
        storagePresenter = new GetStoragePresenter(this, new GetStorageModel());
        //全部库位
        if (type == 0) {
            headers = new String[]{"库存", "近效期"};
            selectTypeOne = new String[]{};
            selectTypeTwo = new String[]{"全部", "近1个月", "近3个月", "近半年", "半年以上"};
            types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY};
            storagePresenter.getStockType(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context));
        } else {
            headers = new String[]{"近效期"};
            selectTypeOne = new String[]{"全部", "近1个月", "近3个月", "近半年", "半年以上"};
            types = new int[]{DropDownMenu.TYPE_LIST_CITY};
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
        }
    }

    @Override
    protected void initData() {
        mData = new ArrayList<>();
        mAdapter = new ProDetailAdapter(mData);
        recyclerView.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(recyclerView);
        mAdapter.setEmptyView(R.layout.empty_view);
    }

    @Override
    protected void bindListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //  MB EPC 过滤设置
//                int Flindex = 1;
//                //ACC PWD
//                String PwdRread = "00000000";
//                //起始地址
//                int Flads = 32;
//                //长度
//                int Fllen = 96;
//                String Fldata = mData.get(position).getSerialNo();
//                //MB RFU  写操作
//                int MbRead = 0;
//                //起始地址，长度
//                int ads = 2;
//                int len = 2;
//                driver.Read_Data_Tag(PwdRread, Flindex, Flads, Fllen, Fldata, MbRead, ads, len);

            }
        });

        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener((index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e(TAG, "===index==" + index + "pos====" + pos);
            if (type==0){
                if (index == 0) {
                    stockName = StockSelList.get(pos).getValue();
                    if (pos == 0) {
                        mDropDownMenu.setTabText(0, "产品库位");
                    }

                } else if (index == 1) {
                    expiryDate = pos;
                    if (pos == 0) {
                        mDropDownMenu.setTabText(1, "近效期");
                    }
                }
            }else {
                if (index == 0) {
                    expiryDate = pos;
                    if (pos == 0) {
                        mDropDownMenu.setTabText(0, "近效期");
                    }
                }
            }
            //网络请求
            loading = false;
            isLoadMore = false;
            pageNum = 1;//设为默认加载第一页
            mData.clear();
            detailPresenter.getInventoryDetail(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),goodsId, stockName,pageSize, pageNum);
//            detailPresenter.getProDetail(manufacturer, productNo, model, stockName, String.valueOf(expiryDate), pageSize, pageNum, type);

        });


        swipe_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                detailPresenter.getInventoryDetail(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),goodsId, stockName,pageSize, pageNum);

//                detailPresenter.getProDetail(manufacturer, productNo, model, stockName, String.valueOf(expiryDate), pageSize, pageNum, type);

            }
        });
            mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    loading = false;
                    isLoadMore = true;
                    detailPresenter.getInventoryDetail(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),goodsId, stockName,pageSize, pageNum);

//                    detailPresenter.getProDetail(manufacturer, productNo, model, stockName, String.valueOf(expiryDate), pageSize, pageNum, type);

                }
            });
        swipe_layout.setRefreshing(true);
        swipe_layout.post(() -> {
            detailPresenter.getInventoryDetail(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),goodsId, stockName,pageSize, pageNum);


//            detailPresenter.getProDetail(manufacturer, productNo, model, stockName, String.valueOf(expiryDate), pageSize, pageNum, type);

        });

    }

    @Override
    public void onResume() {
        super.onResume();
        mDropDownMenu.setFocusableInTouchMode(true);
        mDropDownMenu.requestFocus();
        mDropDownMenu.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        });
    }


    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            if (i == 0) {
                map.put(DropDownMenu.VALUE, selectTypeOne);
                if (stockNameID!=0){
                    map.put(DropDownMenu.SELECT_POSITION,stockNameID );
                }

            } else if (i == 1) {
                map.put(DropDownMenu.VALUE, selectTypeTwo);
                if (expiryDate!=0){
                    map.put(DropDownMenu.SELECT_POSITION, expiryDate);
                }

            }
            viewDatas.add(map);
        }
        return viewDatas;
    }


    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }

    @Override
    public void onGetCategoryListSuccess(ResponseBean responseBean) {
        StockSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (StockSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : StockSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
    }

    @Override
    public void onGetStockTypeSuccess(ResponseBean responseBean) {
        StockSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (StockSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : StockSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        if (mDropDownMenu!=null){
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
        }
    }

    @Override
    public void onGetProDetailSuccess(ResponseBean responseBean) {
//        ProDetailEntity proDetailEntity = (ProDetailEntity) responseBean.pullData();
//        if (proDetailEntity != null)
//            mTvProGuige.setText("规格型号：" + proDetailEntity.getProductModel());
//        mTvProCompany.setText("生产厂商：" + proDetailEntity.getManufacturer());
//        mTvProNum.setText(proDetailEntity.getProductNum());
//        swipe_layout.setRefreshing(false);//完成刷新
//        mData = proDetailEntity.getProductDetailList();
//        if (isLoadMore) {
//            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
//        }
//        if (mData != null && mData.size() > 0) {//有了请求数据
//            if (isLoadMore) {//为true时，是加载更多获取的数据
//                mAdapter.addData(mData);//加载更多的数据，add进去
//            } else {
//                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
//            }
//            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
//                pageNum++;
//                mAdapter.setEnableLoadMore(true);//允许加载更多
//            } else {
//                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
//            }
//
//        } else {
//            if (pageNum == 1) {
//                //数据得清空才会显示空布局
//                mAdapter.getData().clear();
//                mAdapter.notifyDataSetChanged();
//            }
//            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
//        }

    }

    @Override
    public void onGetInventoryDetailSuccess(ResponseBean responseBean) {
        InventoryDetailEntity proDetailEntity = (InventoryDetailEntity) responseBean.pullData();
        if (proDetailEntity != null)
            mTvProGuige.setText("规格型号：" + model);
//        mTvProCompany.setText("生产厂商：" + proDetailEntity.getManufacturer());
        mTvProNum.setText(proDetailEntity.getTotal()+"");
        swipe_layout.setRefreshing(false);//完成刷新
        mData = proDetailEntity.getList();
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
        }
    }

    @Override
    public void onError(String msg) {
        if (isLoadMore) {
            mAdapter.loadMoreFail();//请求失败的话调用loadMoreFail()
        }
        ToastUtils.showText(msg);
    }

    //event 没有管理权限
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishEvent(Event event) {
        if (event.getCode() == EventCode.EventClose) {
            finish();
        }
    }
}